/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.zrb.mobile.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.consts.GlobalConst;
import com.hanhai.common.util.CookieWrapper;
import com.hanhai.zrb.model.common.BaseUser;

/**
 * 前端用的登录工具。
 */
public class FrontLoginUtil {
	
	private static final Logger logger = LoggerFactory
			.getLogger(FrontLoginUtil.class);


	public static final ThreadLocal<BaseUser> currentUser = new ThreadLocal<BaseUser>();

	public static String getCookieValue(HttpServletRequest req,
			HttpServletResponse res, String cookieName) {
		String value = CookieWrapper.getCookieValue(req, cookieName);
		return value;
	}

	public static void setCurrentUser(BaseUser user) {
		currentUser.set(user);

	}

	public static BaseUser getCurrentUser() {
		return currentUser.get();
	}

	public static void initCurrentUser(HttpServletRequest req, Cache loginCache) {
		String key = CookieWrapper.getCookieValue(req,
				GlobalConst.FrontCookieName);
		if (StringUtils.isNotBlank(key)) {
			Object user = loginCache.getValue(key);
			if (user != null) {
				if (user instanceof BaseUser) {
					BaseUser baseUser = (BaseUser) user;
					setCurrentUser(baseUser);
					// 保持登录的情况下，不需要再更新redis中的时间了
					Boolean autoLogin = baseUser.getAutoLogin();
					if (!autoLogin) {
						int timeout = FrontLoginUtil.timeout(autoLogin);
						loginCache.add(key, user, timeout);
					}
				} else {
					logger.error("The user is not front system.");
				}

			}
		}
	}
	
	
	/**
	 * 刷新用户登录缓存
	 * 
	 * 修改用户信息之后调用，如修改了密码，修改了邮箱
	 * 
	 * 前置是需要设置新的 BaseUser到上下文中，调用setCurrentUser(BaseUser user)
	 * @param req
	 * @param loginCache
	 */
	public static void refreshUserCache(HttpServletRequest req, Cache loginCache){
		String key = (String)req.getParameter(GlobalConst.FrontCookieName);		
		BaseUser baseUser = getCurrentUser();
		Boolean autoLogin = baseUser.getAutoLogin();
		int timeout = FrontLoginUtil.timeout(autoLogin);
		loginCache.add(key, baseUser, timeout);
	}
	
	/**
	 * 刷新用户登录缓存，直接传递新的BaseUser进来
	 * 同能同public static void refreshUserCache(HttpServletRequest req, Cache loginCache) 类似
	 * @param req
	 * @param loginCache
	 * @param baseUser
	 */
	public static void refreshUserCache(HttpServletRequest req, Cache loginCache,BaseUser baseUser){
		String key = (String)req.getParameter(GlobalConst.FrontCookieName);		
		setCurrentUser(baseUser);
		Boolean autoLogin = baseUser.getAutoLogin();
		int timeout = FrontLoginUtil.timeout(autoLogin);
		loginCache.add(key, baseUser, timeout);
	}
	
	public static void initCurrentApiUser(HttpServletRequest req, Cache loginCache) {
		/*String key = CookieWrapper.getCookieValue(req,
				GlobalConst.FrontCookieName);*/
		String key = (String)req.getParameter(GlobalConst.FrontCookieName);
		//如果参数中没有，去cookies中找，测试的时候比较方便
		if(StringUtils.isBlank(key)){
			key =  CookieWrapper.getCookieValue(req,
					GlobalConst.FrontCookieName);
		}
		if (StringUtils.isNotBlank(key)) {
			Object user = loginCache.getValue(key);
			if (user != null) {
				if (user instanceof BaseUser) {
					BaseUser baseUser = (BaseUser) user;
					setCurrentUser(baseUser);
					// 保持登录的情况下，不需要再更新redis中的时间了
					Boolean autoLogin = baseUser.getAutoLogin();
					if (!autoLogin) {
						int timeout = FrontLoginUtil.timeout(autoLogin);
						loginCache.add(key, user, timeout);
					}
				} else {
					logger.error("The user is not front system.");
				}

			}
		}
	}
	
	
	public static void removeCurrentApiUser(HttpServletRequest request, HttpServletResponse response,Cache loginCache,String domain){
		String key = (String)request.getParameter(GlobalConst.FrontCookieName);
		//如果参数中没有，去cookies中找，测试的时候比较方便
		if(StringUtils.isBlank(key)){
			key =  CookieWrapper.getCookieValue(request,
					GlobalConst.FrontCookieName);
		}
		
		if (StringUtils.isNotBlank(key)) {
			loginCache.delete(key);
			CookieWrapper.clearCookie(response, GlobalConst.FrontCookieName,
					domain);		
		}
		
	}
	
	public static int checkLoginStatus(BaseUser user){
		return user.getLoginStatus();
	}
	

	public static int timeout(boolean autoLogin) {
		int timeout = GlobalConst.SESSION_TIMEOUT_SECONDS_FRONT;
		if (autoLogin) {
			timeout = GlobalConst.KEEP_LOGIN_TIME_FRONT;
		}
		return timeout;
	}

	public static int expire(boolean autoLogin) {
		int expire = GlobalConst.BROWSER_SESSION_MAX_AGE;
		if (autoLogin) {
			expire = GlobalConst.KEEP_LOGIN_TIME_FRONT;
		}
		return expire;
	}
}
